<template>
	<div class="dishesIndex">
		<el-row :gutter="20">
			<el-col :span="16">
				<el-input
					v-model="name"
					size="large"
					placeholder="请输入套餐名称"
					:prefix-icon="Search"
					@keyup.enter="getTableData"
					style="width: 30%" />
			</el-col>

			<el-col :span="8" class="rightCol">
				<el-button type="danger" text @click="delSetmeal(multipleSelection.map(item => item.id))">批量删除</el-button>
				<el-button type="primary" text @click="updateStatus(multipleSelection, 1)">批量启售</el-button>
				<el-button type="danger" text @click="updateStatus(multipleSelection, 0)">批量停售</el-button>

				<el-button type="primary" color="#ffb600" :icon="Plus" size="large" @click="showDialog('新增')"> 新增套餐 </el-button>
			</el-col>
		</el-row>

		<el-table
			ref="multipleTableRef"
			:data="tableData"
			style="width: 100%; margin-top: 20px"
			@selection-change="handleSelectionChange">
			<el-table-column type="selection" width="55" />
			<el-table-column prop="name" label="套餐名称" align="center" />

			<el-table-column prop="image" label="图片" align="center">
				<template #default="{ row }">
					<el-image
						v-if="row.url"
						style="width: 50px; height: 50px"
						:src="row.url"
						:zoom-rate="1.2"
						:preview-src-list="[row.url]"
						preview-teleported
						fit="cover" />
				</template>
			</el-table-column>

			<el-table-column prop="categoryName" label="套餐分类" align="center" />
			<el-table-column prop="price" label="售价" align="center" />
			<el-table-column prop="status" label="售卖状态" align="center">
				<template #default="{ row }">{{ row.status === 0 ? '停售' : '起售' }}</template>
			</el-table-column>
			<el-table-column prop="updateTime" label="最后操作时间" align="center" />
			<el-table-column fixed="right" label="操作" width="260" align="center">
				<template #default="{ row }">
					<el-button type="primary" text @click="showDialog('修改', row.id)">修改</el-button>
					<el-button type="primary" text @click="updateStatus([row], row.status === 0 ? 1 : 0)">{{
						row.status === 0 ? '起售' : '停售'
					}}</el-button>
					<el-button type="danger" text @click="delSetmeal([row.id])">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<el-pagination
			v-model:current-page="pageNum"
			v-model:page-size="pageSize"
			:page-sizes="[10, 20, 30, 40, 50]"
			layout="total, sizes, prev, pager, next, jumper"
			:total="total"
			@size-change="handleSizeChange"
			@current-change="handleCurrentChange" />

		<ComboManageDialog v-if="dialogParam.dialogVisible" :dialogParam="dialogParam" @dialogClose="dialogClose" />
	</div>
</template>

<script setup lang="ts" name="dishesIndex">
	import { Search, Plus } from '@element-plus/icons-vue'
	import { reactive, ref, toRefs, onMounted } from 'vue'
	import ComboManageDialog from './components/ComboManageDialog.vue'
	import { querySetmealPage, downloadImg, deleteSetmeal, updateSetmealStatus } from '@/api/index'
	import { ElMessage } from 'element-plus'
	import { ItableData } from '@/types'

	interface ISetmealType {
		id: string
		categoryId: string
		name: string
		price: number
		status: number
		code: string
		description: string
		image: string
		updateTime: string
		url?: string
	}

	const tableData = ref<ISetmealType[]>([])

	const total = ref(0)

	const searchParam = reactive({
		name: '',
		pageSize: 10,
		pageNum: 1
	})

	const { name, pageSize, pageNum } = toRefs(searchParam)

	const getImg = async (url: string) => {
		if (url) {
			try {
				const res = await downloadImg<Blob>({ name: url })
				// 使用 window.URL.createObjectURL 将图片流转为地址
				const path = window.URL.createObjectURL(new Blob([res as any], { type: 'image/png' }))
				return path
			} catch (error) {
				console.log('%c [ error ]-112-「comboManage」', 'font-size:13px; background:#f25521; color:#ff9965;', error)
			}

		}
	}

	const getTableData = async () => {
		try {
			const { data } = await querySetmealPage<{ records: ISetmealType[]; total: number }>(searchParam)
			tableData.value = data.records
			total.value = data.total

			const arr: ISetmealType[] = []

			data.records.forEach(async item => {
				await getImg(item.image).then(url => {
					item.url = url
					arr.push(item)
				})

				if (arr.length === data.records.length) {
					tableData.value = arr
				}
			})
		} catch (error) {
			ElMessage.error(error as string)
		}
	}

	const ids = ref<string[]>([])

	const delSetmeal = async (ids: string[]) => {
		console.log('%c [ ids ]-147-「comboManage」', 'font-size:13px; background:#1c109f; color:#6054e3;', ids)
		if (!ids.length) return ElMessage.warning('请选择数据')
		try {
			await deleteSetmeal<string[]>(ids)
			ElMessage.success('删除成功')
			getTableData()
		} catch (error) {
			ElMessage.error(error as string)
		}
	}

	const handleSizeChange = (size: number) => {
		searchParam.pageSize = size
		getTableData()
	}
	const handleCurrentChange = (num: number) => {
		searchParam.pageNum = num
		getTableData()
	}

	const multipleSelection = ref<ISetmealType[]>([])

	const handleSelectionChange = (val: ISetmealType[]) => {
		multipleSelection.value = val

		multipleSelection.value.forEach(item => {
			ids.value.push(item.id)
		})
	}

	interface IDialogType {
		dialogVisible: boolean
		title: string
		id?: string
	}

	const dialogParam = ref<IDialogType>({
		dialogVisible: false,
		title: ''
	})

	const showDialog = (type: string, id?: string) => {
		dialogParam.value.dialogVisible = true
		dialogParam.value.title = type
		dialogParam.value.id = id
	}

	const dialogClose = () => {
		dialogParam.value.dialogVisible = false
		getTableData()
	}

	const updateStatus = async (setmeal: ISetmealType[], status: number) => {
		try {
			if (!setmeal.length) return ElMessage.warning('请选择数据')

			const params = JSON.parse(JSON.stringify(setmeal))

			const res = await updateSetmealStatus<string>(
				params.map((item: ISetmealType) => {
					item.status = status
					return item
				})
			)

			ElMessage.success(res.data)
			getTableData()
		} catch (error) {
			ElMessage.error(error as string)
		}
	}

	onMounted(() => {
		getTableData()
	})
</script>

<style scoped lang="scss">
	.dishesIndex {
		height: 100%;
		padding: 10px;
		background-color: #fff;

		.rightCol {
			display: flex;
			justify-content: flex-end;
			align-items: baseline;
		}
	}
</style>
